package com.git.hui.yinshua.biz.goods.dao.repository;

import com.git.hui.yinshua.api.model.ExceptionUtil;
import com.git.hui.yinshua.api.model.PageReq;
import com.git.hui.yinshua.api.model.Status;
import com.git.hui.yinshua.api.model.constants.GlobalConstants;
import com.git.hui.yinshua.biz.goods.dao.domain.CategoryEntity;
import com.git.hui.yinshua.biz.goods.dao.mapper.CategoryMapper;
import com.git.hui.yinshua.biz.goods.service.CategoryService;
import com.git.hui.yinshua.biz.rest.models.goods.req.CategoryQueryReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author YiHui
 * @date 2024/6/12
 */
@Repository
public class CategoryRepository {
    @Autowired
    private CategoryMapper categoryMapper;

    public String getCategoryName(Integer cid) {
        CategoryEntity entity = categoryMapper.getById(cid);
        return entity == null ? "" : entity.getCategory();
    }

    /**
     * 查询所有生效的分类
     *
     * @return
     */
    public List<CategoryEntity> listAllOnlineCategory() {
        return categoryMapper.list(0, GlobalConstants.MAX_QUERY_SIZE, GlobalConstants.ONLINE_STATE);
    }

    /**
     * 条件查询所有类目，适用于后台管理
     *
     * @param page
     * @return
     */
    public List<CategoryEntity> list(CategoryQueryReq page) {
        return categoryMapper.list(page.getStart(), page.getSize(), page.getState());
    }

    public Integer count() {
        return categoryMapper.count();
    }

    public CategoryEntity save(String category, String intro, Integer state, Integer sort) {
        CategoryEntity dbRecord = categoryMapper.getByCategory(category);
        if (dbRecord != null) {
            throw ExceptionUtil.of(Status.StatusEnum.RECORDS_ALREADY_EXISTS, category);
        }

        CategoryEntity entity = new CategoryEntity();
        entity.setCategory(category == null ? "" : category);
        entity.setIntro(intro == null ? "" : intro);
        entity.setState(state == null ? CategoryService.DISABLE_STATE : CategoryService.ENABLE_STATE);
        entity.setSort(sort == null ? 0 : sort);
        entity.setLevel(1);
        entity.setCode("");
        categoryMapper.saveCategory(entity);
        return entity;
    }

    public Boolean update(CategoryEntity entity) {
        if (entity.getCategory() != null) {
            CategoryEntity dbRecord = categoryMapper.getByCategory(entity.getCategory());
            if (dbRecord != null && !dbRecord.getId().equals(entity.getId())) {
                // 分类名已经存在了
                throw ExceptionUtil.of(Status.StatusEnum.RECORDS_NOT_EXISTS, entity.getCategory());
            }
        }

        return categoryMapper.updateCategory(entity) > 0;
    }
}
